package com.srwl.mytx.widget;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.utils.GlideLoadUtils;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class MyVideoPlayer extends ConstraintLayout {
    private static final String TAG = "MyVideoPlayer";
    private Context context;
    private TextureView surfaceView;
    public PhotoView ivCover;
    public ConstraintLayout container;
    public ImageView ivPlay;
    public ImageView ivBack;
    public TextView tvTitle;
    private String videoPath;
    private Timer timer;
    private MediaPlayer mMediaPlayer;
    private DismissControlViewTimerTask mDismissControlViewTimerTask;
    private int ANIMA_DURING = 400;//毫秒

    public MyVideoPlayer(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public MyVideoPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public MyVideoPlayer(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init();
    }

    private void init() {

        LayoutInflater.from(context).inflate(R.layout.tx_video_player, this);
        surfaceView = findViewById(R.id.surface_view);
        ivCover = findViewById(R.id.iv_cover);
        ivCover.setAnimaDuring(ANIMA_DURING);
        ivCover.setEnabled(false);//不让缩放
        container = findViewById(R.id.container);
        ivPlay = findViewById(R.id.iv_play);
        ivBack = findViewById(R.id.iv_back);
        tvTitle = findViewById(R.id.tv_title);
        ivPlay.setOnClickListener(v -> {
            if (mMediaPlayer.isPlaying()) {
                pauseVideo();
            } else {
                startVideo();
            }


        });
//        surfaceView.setOnTouchListener(new OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
//                if (mMediaPlayer.isPlaying() && event.getAction() == MotionEvent.ACTION_UP) {
//                    ivPlay.setImageResource(R.drawable.jz_click_pause_selector);
//                    ivPlay.setVisibility(VISIBLE);
//                    startDismissControlViewTimer();
//                }
//
//                return false;
//            }
//        });

        surfaceView.setOnClickListener(v -> pauseVideo());
    }

    public void init(String videoPath, String coverPath) {
        this.videoPath = videoPath;
        surfaceView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                initVideo(videoPath);
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {

                stopVideo();
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {

            }
        });

        String path;
        //判断是否是本地地址
        if (coverPath != null && coverPath.contains("/")) {
            path = coverPath;
        } else {
            path = AliOssService.TOPIC_IMAGE_PRE_URL + coverPath;
        }
        //Glide.with(context).load(path).diskCacheStrategy(DiskCacheStrategy.ALL).into(ivCover);
        GlideLoadUtils.glideLoad(context, path, ivCover);
    }


    private void initVideo(String videoPath) {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(3);
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.e(TAG, "onError: 播放器出现错误  :" + extra);
                finishVideo();
                stopVideo();
//                isErrorVideo = true;
//                showToast(getString(R.string.taorecorder_videoerror));
                return false;
            }
        });
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                mMediaPlayer.seekTo(0);
                mMediaPlayer.start();
            }
        });
        // mMediaPlayer.setDisplay(surfaceHolder);
        mMediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {

                Log.i(TAG, "onInfo:执行了，，， ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,");
                ivCover.setVisibility(View.GONE);
                return false;
            }
        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.i(TAG, "onPrepared: 播放器准备好了");
            }
        });
        mMediaPlayer.setSurface(new Surface(surfaceView.getSurfaceTexture()));

        try {
            mMediaPlayer.setDataSource(videoPath);
            mMediaPlayer.prepare();
        } catch (IllegalArgumentException var2) {
            var2.printStackTrace();
        } catch (SecurityException var3) {
            var3.printStackTrace();
        } catch (IllegalStateException var4) {
            var4.printStackTrace();
        } catch (IOException var5) {
            var5.printStackTrace();
        }

//        if (anim_playbutton == null) {
//            anim_playbutton = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.taorecorder_alpha_hide);
//            anim_playbutton.setAnimationListener(new Animation.AnimationListener() {
//                public void onAnimationStart(Animation animation) {
//                }
//
//                public void onAnimationEnd(Animation animation) {
//                    if (!isErrorVideo) {
//                        iv_playbutton.setVisibility(View.GONE);
//                    }
//
//                }
//
//                public void onAnimationRepeat(Animation animation) {
//                }
//            });
//        }

    }


    public void startVideo() {
        if (mMediaPlayer == null) {
            return;
        }
        mMediaPlayer.start();
        ivPlay.setVisibility(View.GONE);
        //iv_playbutton.startAnimation(anim_playbutton);
    }

    public void pauseVideo() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            ivPlay.setVisibility(View.VISIBLE);
        }
    }

    public void finishVideo() {
        ivCover.setVisibility(View.VISIBLE);
        ivPlay.setVisibility(View.VISIBLE);
    }


    public void stopVideo() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }

        ivCover.setVisibility(View.VISIBLE);
        ivPlay.setVisibility(View.VISIBLE);
        surfaceView.setVisibility(INVISIBLE);

    }


    public void startDismissControlViewTimer() {
        cancelDismissControlViewTimer();
        timer = new Timer();
        mDismissControlViewTimerTask = new DismissControlViewTimerTask();
        timer.schedule(mDismissControlViewTimerTask, 2500);
    }

    public void cancelDismissControlViewTimer() {
        if (timer != null) {
            timer.cancel();
        }
        if (mDismissControlViewTimerTask != null) {
            mDismissControlViewTimerTask.cancel();
        }

    }

    /**
     * 从大图过度到小图的动画
     *
     * @param smallImageViewInfo
     */
    public void animateExit(Info smallImageViewInfo) {
        Info bigImageViewInfo = PhotoView.getBigImageViewInfo(ivCover);
        if (smallImageViewInfo == null || bigImageViewInfo == null) {
            return;
        }
        RectF bigImageRectF = bigImageViewInfo.getmImgRect();
        RectF smallRectF = smallImageViewInfo.getmBaseRect();
        float scaleX = smallRectF.width() / bigImageRectF.width();
        float scaleY = smallRectF.height() / bigImageRectF.height();
        float translationY = bigImageViewInfo.getmRect().centerY() - smallImageViewInfo.getmRect().centerY();
        float translationX = bigImageViewInfo.getmRect().centerX() - smallImageViewInfo.getmRect().centerX();
        //小图的播放图标是30dp,而大屏视频中的播放按键图标是45dp,由此计算缩放比例 30/50=0.7
        ViewAnimator.animate(ivPlay).scale(1, 0.7f).translationY(0, -translationY).translationX(0, -translationX).duration(ANIMA_DURING).start();
        ViewAnimator.animate(container).scaleX(scaleX).scaleY(scaleY).alpha(1, 0).translationY(0, -translationY).translationX(0, -translationX).duration(ANIMA_DURING / 2).start();
        // ViewAnimator.animate(ivCover).scaleX(scaleX).scaleY(scaleY).translationY(0, -translationY).translationX(0, -translationX).duration(400).start();
        ivCover.animaTo(smallImageViewInfo, new Runnable() {
            @Override
            public void run() {

            }
        });
    }

    /**
     * 从小图过度到大图的动画
     *
     * @param smallImageViewInfo
     */
    public void animateEnter(Info smallImageViewInfo) {
        if (smallImageViewInfo == null) {
            return;
        }
        Rect outRect = new Rect();
        ivCover.getHitRect(outRect);
        RectF smallRect = smallImageViewInfo.getmBaseRect();
        float scaleX = smallRect.width() / outRect.width();
        float scaleY = smallRect.height() / outRect.height();
        float translationY = outRect.centerY() - smallImageViewInfo.getmRect().centerY();
        float translationX = outRect.centerX() - smallImageViewInfo.getmRect().centerX();
        ViewAnimator.animate(ivPlay).scale(0.7f, 1).translationY(-translationY, 0).translationX(-translationX, 0).duration(ANIMA_DURING).start();
        ViewAnimator.animate(container).scaleX(scaleX, 1).scaleY(scaleY, 1).alpha(0, 1).translationY(-translationY, 0).translationX(-translationX, 0).duration(ANIMA_DURING).start();
        //  ViewAnimator.animate(ivCover).scaleX(scaleX, 1).scaleY(scaleY, 1).translationY(-translationY, 0).translationX(-translationX, 0).duration(400).start();
        ivCover.animaFrom(smallImageViewInfo);

    }

    public class DismissControlViewTimerTask extends TimerTask {

        @Override
        public void run() {
            dissmissControlView();
        }
    }

    public void dissmissControlView() {

        post(() -> {
            ivPlay.setVisibility(View.INVISIBLE);

        });

    }
}
